﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Net;
using System.IO;

namespace DLULearningNetwork.Libs
{
    public static class ReCaptchaHelper
    {
        public static MvcHtmlString GenerateCaptcha(this HtmlHelper htmlHelper, string publicKey)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type='text/javascript'> var RecaptchaOptions = { theme: 'custom', custom_theme_widget: 'recaptcha_widget', lang :'en' };</script>");
            sb.Append("<div id='recaptcha_widget' style='display: none'>");
            sb.Append("<div id='recaptcha_image' style='float:left;padding-left:20px;'></div>");
            sb.Append("<div style='float:right;padding-top:15px'> <img onclick='Recaptcha.reload()' alt='' src='../../Content/Images/refresh.png' style='border:0px;width:30px;height:30px'/></div>");
            sb.Append("<div style='clear:both'><span class='recaptcha_only_if_image'>Nhập hai chữ trong hình</span> <span class='recaptcha_only_if_audio'>Nhập số mà bạn nghe:</span>");
            sb.Append("<input type='text' id='recaptcha_response_field' name='recaptcha_response_field' /></div>");
            sb.Append("</div>");
            sb.AppendFormat("<script type='text/javascript' src='http://www.google.com/recaptcha/api/challenge?k={0}'> </script> ", publicKey);
            sb.Append("<noscript>");
            sb.AppendFormat("<iframe src='http://www.google.com/recaptcha/api/noscript?k={0}'  height='300' width='500' frameborder='0'>", publicKey);
            sb.Append("</iframe>");
            sb.Append("<br/>");
            sb.Append("<textarea name='recaptcha_challenge_field' rows='3' cols='40'>   </textarea>");
            sb.Append("<input type='hidden' name='recaptcha_response_field' value='manual_challenge'/>");
            sb.Append("</noscript>");
            return new MvcHtmlString(sb.ToString());
        }
        public static bool Validate(string remoteIP, string captchaChallenge, string captchaResponse)
        {
            bool result = false;
            string response = GetWebResponse(remoteIP, captchaChallenge, captchaResponse);
            result = response.ToLower().StartsWith("true");  //api response line 1 value: true or false
            return result;
        }
        static string GetWebResponse(string remoteIP, string captchaChallenge, string captchaResponse)
        {
            string result = null;

            //convert params to byte array
            var parameters = string.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}",
                                           Constants.RECAPTCHA_PRIVATE_KEY, remoteIP, captchaChallenge, captchaResponse);
            byte[] paramData = Encoding.UTF8.GetBytes(parameters);

            var request = (HttpWebRequest)WebRequest.Create(Constants.RECAPTCHA_VERIFY_URL);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = paramData.Length;
            request.ServicePoint.Expect100Continue = false;

            //write param data to request stream
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(paramData, 0, paramData.Length);
                requestStream.Close();
            }

            using (WebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader responseReader = new StreamReader(stream))
                    {
                        result = responseReader.ReadToEnd();
                        responseReader.Close();
                    }
                    stream.Close();
                }
                response.Close();
            }
            return result;
        }
    }
}